import EchartsComponent, { MyChartOption, MyChartRef } from '@/components/EchartsComponent';
import React, { useEffect, useRef, useState } from 'react';
import { useIntl } from 'umi';
import Styles from './index.less';
import PieLegend from './PieLegend';

interface IProps {
  pcsViewInfo: API.PcsDataDTO['statusList'];
}

export const PieChart: React.FC<IProps> = ({ pcsViewInfo }) => {
  const intl = useIntl();
  const chartRef = useRef<MyChartRef>(null);
  const [PcsChart, setPcsChart] = useState<MyChartOption>({
    legend: {
      show: false,
      top: 100,
      right: 'right',
      icon: 'circle',
    },
    series: [
      {
        name: 'Access From',
        type: 'pie',
        radius: ['50%', '70%'],
        label: {
          position: 'center',
          formatter: `0\n${intl.formatMessage({ id: 'stationRealtimeMonitoring.totalPcs' })}`,
        },
        labelLine: { show: false },
        data: [
          {
            value: 0,
            name: intl.formatMessage({ id: 'stationRealtimeMonitoring.standby' }),
            itemStyle: { color: '#3586FF' },
          },
          {
            value: 0,
            name: intl.formatMessage({ id: 'stationRealtimeMonitoring.charging' }),
            itemStyle: { color: '#FB4A58' },
          },
          {
            value: 0,
            name: intl.formatMessage({ id: 'stationRealtimeMonitoring.discharging' }),
            itemStyle: { color: '#FF7A0C' },
          },
          {
            value: 0,
            name: intl.formatMessage({ id: 'stationRealtimeMonitoring.fault' }),
            itemStyle: { color: '#FFD50C' },
          },
          {
            value: 0,
            name: intl.formatMessage({ id: 'stationRealtimeMonitoring.other' }),
            itemStyle: { color: '#F0F1F5' },
          },
        ],
      },
    ],
  });
  const selectColor = (value: string) => {
    const echartsInstance = chartRef.current?.instance();
    echartsInstance?.dispatchAction({
      type: 'legendToggleSelect',
      name: value,
    });
  };

  const changePcsInfo = (pcsViewInfo: IProps) => {
    let obj = {
      standby: {
        rate: 0,
        num: 0,
      },
      charge: {
        rate: 0,
        num: 0,
      },
      discharge: {
        rate: 0,
        num: 0,
      },
      fault: {
        rate: 0,
        num: 0,
      },
      other: {
        rate: 0,
        num: 0,
      },
    };

    if (pcsViewInfo && pcsViewInfo?.length > 0) {
      let totalSum = 0;
      pcsViewInfo.forEach((item) => {
        totalSum += Number(item?.num || 0);
      });
      const pcsViewInfoMap = new Map([
        [0, 'other'],
        [2, 'standby'],
        [3, 'charge'],
        [4, 'discharge'],
        [5, 'fault'],
      ]);

      for (let i = 0; i < pcsViewInfo.length; i++) {
        let key = pcsViewInfoMap.get(pcsViewInfo[i]['workState']);
        obj[key]['num'] = Number(pcsViewInfo[i]['num']);

        obj[key]['rate'] =
          totalSum === 0
            ? Number(0).toFixed(2)
            : ((pcsViewInfo[i]['num'] / totalSum) * 100).toFixed(2);
      }
    }

    return obj;
  };

  useEffect(() => {
    if (pcsViewInfo) {
      let totalSum = 0;
      pcsViewInfo.forEach((item) => {
        totalSum += Number(item?.num || 0);
      });

      let pcsViewInfoCopy = changePcsInfo(pcsViewInfo);

      setPcsChart({
        legend: {
          show: false,
          left: 480,
          top: 60,
          right: 'right',
          icon: 'circle',
          itemGap: 20,
          formatter: function (name) {
            console.log('value', name);
            return `${name}`;
          },
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['50%', '70%'],
            label: {
              position: 'center',
              formatter: [
                `{a|${totalSum}}`,
                `{b|${intl.formatMessage({ id: 'stationRealtimeMonitoring.GLCTotal' })}}`,
              ].join('\n'),
              rich: {
                a: {
                  fontSize: 18,
                },
                b: {
                  fontSize: 16,
                },
              },
            },
            labelLine: { show: false },
            data: [
              {
                value: pcsViewInfoCopy?.standby?.rate || 0,
                name: intl.formatMessage({ id: 'stationRealtimeMonitoring.standby' }),
                itemStyle: { color: 'yellow' },
              },
              {
                value: pcsViewInfoCopy?.charge?.rate || 0,
                name: intl.formatMessage({ id: 'stationRealtimeMonitoring.charging' }),
                itemStyle: { color: 'green' },
              },
              {
                value: pcsViewInfoCopy?.discharge?.rate || 0,
                name: intl.formatMessage({ id: 'stationRealtimeMonitoring.discharging' }),
                itemStyle: { color: 'blue' },
              },
              {
                value: pcsViewInfoCopy?.fault?.rate || 0,
                name: intl.formatMessage({ id: 'stationRealtimeMonitoring.fault' }),
                itemStyle: { color: 'red' },
              },
              {
                value: pcsViewInfoCopy?.other?.rate || 0,
                name: intl.formatMessage({ id: 'stationRealtimeMonitoring.other' }),
                itemStyle: { color: '#F0F1F5' },
              },
            ],
          },
        ],
      });
    }
  }, [pcsViewInfo]);
  return (
    <>
      <div className={Styles.chrtWrap}>
        <div className={Styles.chrtWrap_pie}>
          <EchartsComponent
            ref={chartRef}
            option={PcsChart}
            width={'239px'}
            height={'240px'}
          ></EchartsComponent>
        </div>

        <div className={Styles.chrtWrap_pielenged}>
          <PieLegend pcsViewInfo={changePcsInfo(pcsViewInfo)} selectColor={selectColor} />
        </div>
      </div>
    </>
  );
};
